<!-- #layout name=default -->
<div id="main">
  <div class="page-header">
    <h1 class="title"><span>Data table</span>: <strong>{{name}}</strong></h1>
  </div>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a
        href="javascript:;"
        class="btn green navbar-btn"
        @click="onShowEditColumnModal()"
        >New column</a
      >
    </div>
  </div>
  <table class="table table-striped table-hover">
    <thead>
      <tr>
        <th>Column name</th>
        <th class="table-short">Control type</th>
        <th class="table-short">Primary key</th>
        <th class="table-short">Unique</th>
        <th class="table-short">Index</th>
        <th class="table-action"></th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item,index) in columns" :key="index">
        <td>
          <a href="javascript:;" @click="onShowEditColumnModal(item)"
            >{{item.name}}</a
          >
        </td>
        <td
          >{{item.controlType ?
          Kooboo.columnEditor.controlTypeNames[item.controlType.toLowerCase()] :
          ""}}</td
        >
        <td>
          <span
            class="label label-sm"
            :class="{'label-default': !item.isPrimaryKey, 'green': item.isPrimaryKey}"
            >{{Kooboo.text.common[item.isPrimaryKey ? 'yes' : 'no']}}</span
          >
        </td>
        <td>
          <span
            class="label label-sm"
            :class="{ 'label-default': !item.isUnique, 'green': item.isUnique }"
            >{{ Kooboo.text.common[item.isUnique ? 'yes' : 'no']}}</span
          >
        </td>
        <td>
          <span
            class="label label-sm"
            :class="{ 'label-default': !item.isIndex, 'green': item.isIndex }"
            >{{Kooboo.text.common[item.isIndex ? 'yes' : 'no']}}</span
          >
        </td>
        <td>
          <a
            v-if="!item.isSystem"
            href="javascript:;"
            class="btn btn-xs red"
            @click="removeColumn(item)"
            >{{Kooboo.text.common.remove}}</a
          >
        </td>
      </tr>
    </tbody>
  </table>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showEditColumnModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" data-dismiss="modal"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title"
            >{{Kooboo.text.component.columnEditor.title}}</h4
          >
        </div>
        <div class="modal-body" v-if="showEditColumnModal">
          <kb-form
            :model="columnModel"
            :rules="columnModelRules"
            ref="columnForm"
          >
            <kb-form-item prop="name">
              <label class="col-md-3 control-label"
                >{{ Kooboo.text.common.name}}</label
              >
              <div class="col-md-9">
                <input
                  v-if="isNew"
                  type="text"
                  class="form-control"
                  v-model="columnModel.name"
                />
                <p
                  v-else
                  class="form-control-static"
                  style="word-break: break-all;"
                  >{{columnModel.name}}</p
                >
              </div>
            </kb-form-item>
            <kb-form-item>
              <label class="col-md-3 control-label"
                >{{Kooboo.text.component.fieldEditor.controlType}}</label
              >
              <div class="col-md-9">
                <select
                  v-if="availableControlTypes.length > 1 "
                  class="form-control"
                  v-model="columnModel.controlType"
                  @click="resetColumnModel"
                >
                  <option
                    v-for="item in availableControlTypes"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{item.displayName}}
                  </option></select
                >
                <p v-else class="form-control-static"
                  >{{columnModel.controlType?Kooboo.columnEditor.controlTypeNames[columnModel.controlType.toLowerCase()]
                  : ''}}</p
                >
              </div>
            </kb-form-item>
            <kb-form-item v-if="showStringLengthForm" prop="length">
              <label class="col-md-3 control-label">Length</label>
              <div class="col-md-9">
                <input
                  type="number"
                  class="form-control"
                  min="1"
                  v-model="columnModel.length"
                />
              </div>
            </kb-form-item>
            <kb-form-item v-kb-collapsein="showOptionForm">
              <label class="col-md-3 control-label">Options</label>
              <div class="col-md-9" v-if="columnModel.setting">
                <div class="input-groups">
                  <div
                    v-for="(item,index) in columnModel.setting.options"
                    class="input-group"
                    :class="{'has-error':item.init&&(!item.leftValid||!item.rightValid)}"
                  >
                    <input
                      type="text"
                      class="form-control key input-small"
                      :placeholder="Kooboo.text.common.displayName"
                      v-model="item.key"
                      v-kb-tooltip:left.manual.error="validOption(item,item.leftValid)"
                      @input="validOptions(columnModel.setting.options)"
                    />
                    <span class="input-group-addon">:</span>
                    <input
                      type="text"
                      class="form-control value input-small"
                      :placeholder="Kooboo.text.common.value"
                      v-model="item.value"
                      @input="validOptions(columnModel.setting.options)"
                    />
                    <span
                      class="input-group-btn"
                      v-kb-tooltip:right.manual.error="validOption(item,item.rightValid)"
                      ><a
                        class="btn btn-default"
                        href="javascript:;"
                        @click="removeOption(columnModel.setting.options,item)"
                        ><i class="fa fa-minus"></i></a
                    ></span>
                  </div>
                </div>
                <div>
                  <a
                    class="btn dark"
                    href="javascript:;"
                    @click="addOption(columnModel.setting.options)"
                    :disabled="!validOptions(columnModel.setting.options)"
                    v-kb-tooltip:right.manual.error="optionsEmptyMsg"
                    ><i class="fa fa-plus"></i
                  ></a>
                </div>
              </div>
            </kb-form-item>
            <kb-form-item
              v-kb-collapsein="columnModel.controlType&&columnModel.controlType.toLowerCase()=='number'"
            >
              <div class="col-md-offset-3 col-md-9">
                <label class="checkbox-inline">
                  <input
                    type="checkbox"
                    v-model="columnModel.isIncremental"
                    :disabled="disableIncremental"
                  />
                  <span>
                    {{Kooboo.text.component.columnEditor.incremental}}</span
                  >
                </label>
              </div>
            </kb-form-item>
            <kb-form-item
              v-kb-collapsein="columnModel.isIncremental"
              prop="seed"
            >
              <label class="col-md-3 control-label"
                >{{Kooboo.text.component.columnEditor.seed}}</label
              >
              <div class="col-md-9">
                <input
                  type="number"
                  ref="seedInput"
                  min="1"
                  class="form-control"
                  @keydown="inputNumberOnly"
                  v-model="columnModel.seed"
                />
              </div>
            </kb-form-item>
            <kb-form-item
              v-kb-collapsein="columnModel.isIncremental"
              prop="scale"
            >
              <label class="col-md-3 control-label"
                >{{Kooboo.text.component.columnEditor.scale}}</label
              >
              <div class="col-md-9">
                <input
                  type="number"
                  ref="scaleInput"
                  min="1"
                  class="form-control"
                  @keydown="inputNumberOnly"
                  v-model="columnModel.scale"
                />
              </div>
            </kb-form-item>
            <kb-form-item>
              <div class="col-md-offset-3 col-md-9">
                <label class="checkbox-inline">
                  <input type="checkbox" v-model="columnModel.isPrimaryKey" />
                  <span>{{Kooboo.text.component.columnEditor.primaryKey}}</span>
                </label>
                <label class="checkbox-inline">
                  <input type="checkbox" v-model="columnModel.isUnique" />
                  <span>{{Kooboo.text.component.columnEditor.unique}}</span>
                </label>
                <label class="checkbox-inline">
                  <input type="checkbox" v-model="columnModel.isIndex" />
                  <span>{{Kooboo.text.component.columnEditor.index}}</span>
                </label>
              </div>
            </kb-form-item>
          </kb-form>
        </div>
        <div class="modal-footer">
          <a href="javascript:;" class="btn green" @click="onEditorSave"
            >{{Kooboo.text.common.save}}</a
          >
          <a href="javascript:;" class="btn gray" data-dismiss="modal"
            >{{Kooboo.text.common.cancel}}</a
          >
        </div>
      </div>
    </div>
  </div>

  <div class="page-buttons">
    <button @click="onSave" class="btn green">Save</button>
    <a :href="returnUrl" class="btn gray">Cancel</a>
  </div>
</div>
<script>
  Kooboo.loadJS(["/_Admin/Scripts/components/kbForm.js"]);
  Kooboo.columnEditor = {};
  Kooboo.columnEditor.controlTypes = [
    {
      displayName: Kooboo.text.component.controlType.textBox,
      value: "TextBox",
      dataType: "String"
    },
    {
      displayName: Kooboo.text.component.controlType.textArea,
      value: "TextArea",
      dataType: "String"
    },
    {
      displayName: Kooboo.text.component.controlType.wysiwygEditor,
      value: "Tinymce",
      dataType: "String"
    },
    {
      displayName: Kooboo.text.component.controlType.selection,
      value: "Selection",
      dataType: "Undefined"
    },
    {
      displayName: Kooboo.text.component.controlType.checkBox,
      value: "CheckBox",
      dataType: "Undefined"
    },
    {
      displayName: Kooboo.text.component.controlType.radioBox,
      value: "RadioBox",
      dataType: "Undefined"
    },
    {
      displayName: Kooboo.text.component.controlType.boolean,
      value: "Boolean",
      dataType: "Bool"
    },
    {
      displayName: Kooboo.text.component.controlType.dateTime,
      value: "DateTime",
      dataType: "DateTime"
    },
    {
      displayName: Kooboo.text.component.controlType.number,
      value: "Number",
      dataType: "Number"
    }
  ];
  Kooboo.columnEditor.controlTypeNames = {};
  Kooboo.columnEditor.controlTypes.forEach(function(t) {
    Kooboo.columnEditor.controlTypeNames[t.value.toLowerCase()] = t.displayName;
  });
  var CONTROL_TYPES = Kooboo.columnEditor.controlTypes;

  new Vue({
    el: "#main",
    data: function() {
      var me = this;
      return {
        name: Kooboo.getQueryString("table"),
        from: Kooboo.getQueryString("from"),
        columns: [],
        showEditColumnModal: false,
        isNew: false,
        optionsEmptyMsg: "",
        selectedColumn: null,
        columnModel: {
          name: "",
          dataType: "String",
          isIncremental: false,
          seed: 1,
          scale: 1,
          isIndex: false,
          isPrimaryKey: false,
          isUnique: false,
          controlType: "TextBox",
          isSystem: false,
          length: 1024,
          setting: {
            options: [],
            validations: []
          }
        },
        columnModelRules: {
          name: [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              max: 64,
              message: Kooboo.text.validation.maxLength + " 64"
            },
            {
              validate: function(value) {
                if (!me.isNew) return true;
                return !me.columns.find(function(f) {
                  return f.name == value;
                });
              },
              message: Kooboo.text.validation.taken
            }
          ],
          length: [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              message: Kooboo.text.validation.minLength + " 1"
            },
            {
              pattern: /^[0-9]*$/,
              message: Kooboo.text.validation.taken
            }
          ],
          seed: [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              message: Kooboo.text.validation.minLength + " 1"
            }
          ],
          scale: [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              message: Kooboo.text.validation.minLength + " 1"
            }
          ]
        }
      };
    },
    methods: {
      onShowEditColumnModal: function(item) {
        if (item) {
          this.handleColumn(item);
          this.selectedColumn = item;
          this.columnModel = JSON.parse(JSON.stringify(item));
          this.isNew = false;
        } else {
          this.columnModel = {
            name: "",
            dataType: "String",
            isIncremental: false,
            seed: 1,
            scale: 1,
            isIndex: false,
            isPrimaryKey: false,
            isUnique: false,
            controlType: "TextBox",
            isSystem: false,
            length: 1024,
            setting: {
              options: []
            }
          };
          this.isNew = true;
        }
        this.showEditColumnModal = true;
        this.$nextTick(function() {
          this.$refs.seedInput.onkeydown = this.inputNumberOnly;
          this.$refs.scaleInput.onkeydown = this.inputNumberOnly;
        });
      },
      removeColumn: function(item) {
        if (confirm(Kooboo.text.confirm.deleteItem)) {
          this.columns = this.columns.filter(function(i) {
            return i != item;
          });
        }
      },
      onSave: function() {
        var me = this;
        me.columns.forEach(function(i) {
          if (i.setting) {
            i.setting.options.forEach(function(o) {
              delete o.init;
              delete o.leftValid;
              delete o.rightValid;
            });
            i.setting = JSON.stringify(i.setting);
          }
        });
        Kooboo.Database.updateColumn({
          tableName: me.name,
          columns: me.columns
        }).then(function(res) {
          if (res.success) {
            location.href = me.returnUrl;
          }
        });
      },
      onEditorSave: function() {
        var valid = true;
        valid = valid & this.$refs.columnForm.validate();
        if (this.columnModel.setting) {
          this.columnModel.setting.options.forEach(function(i) {
            i.init = true;
          });
          valid = valid & this.validOptions(this.columnModel.setting.options);
        }
        if (this.showOptionForm) {
          if (!this.columnModel.setting.options.length) {
            valid = false;
            this.optionsEmptyMsg = Kooboo.text.validation.required;
          }
        }
        if (!valid) return;

        if (this.isNew) {
          this.columns.push(this.columnModel);
        } else {
          var index = this.columns.indexOf(this.selectedColumn);
          this.columns.splice(index, 1, this.columnModel);
        }

        if (this.columnModel.isPrimaryKey) {
          this.columns.forEach(function(col) {
            col.isPrimaryKey = false;
          });
          this.columnModel.isPrimaryKey = true;
        }
        this.showEditColumnModal = false;
      },
      addOption: function(options) {
        if (!this.validOptions(options)) return;
        this.optionsEmptyMsg = "";
        options.push({
          key: "",
          value: "",
          init: false,
          leftValid: false,
          rightValid: false
        });
      },
      validOptions: function(options) {
        var allValid = true;
        options.forEach(function(opt) {
          opt.leftValid = !!opt.key.trim();
          opt.rightValid = !!opt.value.trim();
          if (!opt.leftValid || !opt.rightValid) {
            allValid = false;
          }
        });
        return allValid;
      },
      removeOption: function(options, item) {
        options.splice(options.indexOf(item), 1);
      },
      validOption: function(item, option) {
        if (!item.init) return "";
        return option ? "" : Kooboo.text.validation.required;
      },
      handleColumn: function(column) {
        if (column.setting && typeof column.setting == "string") {
          column.setting = JSON.parse(column.setting);
          column.setting.options.forEach(function(i) {
            i.init = false;
            i.leftValid = false;
            i.rightValid = false;
          });
        }
      },
      resetColumnModel: function() {
        this.columnModel.isIncremental = false;
        this.columnModel.seed = 1;
        this.columnModel.scale = 1;
        if (this.columnModel.setting) {
          this.columnModel.setting.options = [];
        }
      },
      inputNumberOnly: function(e) {
        if (e.keyCode >= 48 && e.keyCode <= 57 /*number*/) {
          return true;
        } else if (e.keyCode >= 96 && e.keyCode <= 105 /*number*/) {
          return true;
        } else if (e.keyCode == 8 /*BACKSPACE*/) {
          return true;
        } else {
          return false;
        }
      }
    },
    mounted: function() {
      var me = this;
      if (this.name) {
        Kooboo.Database.getColumns({
          table: this.name
        }).then(function(res) {
          if (res.success) {
            me.columns = res.model;
            me.columns.forEach(function(m) {
              me.handleColumn(m);
            });
          } else {
            setTimeout(function() {
              location.href = self.returnUrl();
            }, 1000);
          }
        });
      } else {
        window.info.fail(Kooboo.text.info.parameterMissing + ": table");
        setTimeout(function() {
          location.href = this.returnUrl;
        }, 1000);
      }
    },
    computed: {
      returnUrl: function() {
        if (this.from) {
          return Kooboo.Route.Get(Kooboo.Route.Database.DataPage, {
            table: this.name
          });
        } else {
          return Kooboo.Route.Database.TablePage;
        }
      },
      availableControlTypes: function() {
        var me = this;
        if (this.isNew) {
          return Kooboo.columnEditor.controlTypes;
        } else {
          var groups = _.groupBy(CONTROL_TYPES, "dataType"),
            find = _.find(CONTROL_TYPES, function(ct) {
              return ct.value == me.columnModel.controlType;
            });
          return find ? groups[find.dataType] : [];
        }
      },
      disableIncremental: function() {
        return (
          this.columnModel.controlType == "Number" &&
          !this.columnModel.isIncremental &&
          !this.isNew
        );
      },
      showStringLengthForm: function() {
        if (!this.columnModel.controlType) {
          return false;
        } else {
          return (
            ["textbox", "textarea", "tinymce"].indexOf(
              this.columnModel.controlType.toLowerCase()
            ) > -1
          );
        }
      },
      showOptionForm: function() {
        if (!this.columnModel.controlType) {
          return false;
        } else {
          return (
            ["selection", "checkbox", "radiobox"].indexOf(
              this.columnModel.controlType.toLowerCase()
            ) > -1
          );
        }
      },
      controlTypeName: function() {
        return this.columnModel.controlType
          ? Kooboo.columnEditor.controlTypeNames[
              this.columnModel.controlType.toLowerCase()
            ]
          : "";
      }
    },
    watch: {
      "columnModel.isPrimaryKey": function(value) {
        if (value) this.columnModel.isUnique = true;
      },
      "columnModel.isUnique": function(value) {
        if (value) {
          this.columnModel.isIndex = true;
        } else if (
          this.columnModel.isIncremental ||
          this.columnModel.isPrimaryKey
        ) {
          this.$nextTick(function() {
            this.columnModel.isUnique = true;
          });
        }
      },
      "columnModel.isIndex": function(value) {
        if (!value && this.columnModel.isUnique) {
          this.$nextTick(function() {
            this.columnModel.isIndex = true;
          });
        }
      },
      "columnModel.isIncremental": function(value) {
        this.columnModel.isUnique = value;
        this.columnModel.isIndex = value;
      },
      "columnModel.controlType": function(value) {
        this.columnModel.dataType = Kooboo.columnEditor.controlTypes.find(
          function(f) {
            return f.value == value;
          }
        ).dataType;
      },
      showOptionForm: function() {
        this.optionsEmptyMsg = "";
      }
    }
  });
</script>
